package com.qumitech.visualnovel.service.location.impl;

import com.alibaba.fastjson.JSONObject;
import com.qumitech.visualnovel.component.util.HttpInvokeUtil;
import com.qumitech.visualnovel.model.common.BaseRsp;
import com.qumitech.visualnovel.model.dao.console.UserInfo;
import com.qumitech.visualnovel.model.common.UrlConstant;
import com.qumitech.visualnovel.pubdef.dto.location.LocationBlockAdminDTO;
import com.qumitech.visualnovel.pubdef.dto.location.LocationBlockAdminQueryDTO;
import com.qumitech.visualnovel.service.location.LocationService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service
public class LocationServiceImpl implements LocationService {

    private final String LOCATION_BLOCK_CONSOLE_URL = "/location/block/console/plane";

    @Override
    public BaseRsp invalidLocationBlock(LocationBlockAdminDTO dto) {
        dto.setOperator(getActiveUserName());
        String url = UrlConstant.SERVER_URL + LOCATION_BLOCK_CONSOLE_URL+"/" + dto.getBlockId();
        String req = JSONObject.toJSONString(dto);
        String body = HttpInvokeUtil.httpPostJson(url, req, UrlConstant.DefaultEncode, null);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp saveLocationBlock(LocationBlockAdminDTO dto) {
        dto.setOperator(getActiveUserName());
        String url = UrlConstant.SERVER_URL + LOCATION_BLOCK_CONSOLE_URL;
        String req = JSONObject.toJSONString(dto);
        String body = HttpInvokeUtil.httpPostJson(url, req, UrlConstant.DefaultEncode, null);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp listLocationBlock(LocationBlockAdminQueryDTO queryDTO) {
        String url = UrlConstant.SERVER_URL + LOCATION_BLOCK_CONSOLE_URL;
        JSONObject o = JSONObject.parseObject(JSONObject.toJSONString(queryDTO));

        Map<String, Object> req = JSONObject.toJavaObject(o, Map.class);
        String body = HttpInvokeUtil.httpGet(url, req);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    private String getActiveUserName(){
        Subject subject = SecurityUtils.getSubject();
        UserInfo activeUser = (UserInfo) subject.getPrincipal();
        return activeUser.getUsername();
    }

}
